package cn.sunxyz.module.honey.web;

import cn.sunxyz.common.site.Result;
import cn.sunxyz.common.site.controller.DefaultController;
import cn.sunxyz.common.util.DateRandom;
import cn.sunxyz.module.honey.domain.FolderDO;
import cn.sunxyz.module.honey.domain.vo.FileCollection;
import cn.sunxyz.module.honey.repository.FolderRepository;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 文件夹
 * Created by sunxyz on 2017/3/2.
 */
@RestController
@RequestMapping("/api/folder")
public class FolderController extends DefaultController<FolderRepository, FolderDO, Long> {

    @PostMapping
    public Result<String> addFolder(@RequestParam(name = "pid", required = false) FolderDO parent, FolderDO folderDO) {
        String path = DateRandom.random36String();
        //设置路径名称
        if (Objects.nonNull(parent)) {
            folderDO.setParent(parent);
            folderDO.setFullPath(parent.getSelfPathName() + "/" + path);
        } else {
            folderDO.setFullPath(path);
        }
        folderDO.setSelfPathName(path);
        return super.add(folderDO);
    }

    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        return super.delete(id);
    }

    @PutMapping("/{id}")
    public Result<String> update(@PathVariable("id") FolderDO folder, FolderDO news) {
        folder.setName($(folder::getName, news::getName));
        folder.setDescription($(folder::getDescription, news::getDescription));
        return super.update(folder);
    }

    /**
     * 根据文件夹id获取文件集合(子文件夹，子文件)
     * Created by sunxyz on 2017/3/3.
     */
    @GetMapping("/{path}")
    public Result<?> getFileCollection(@PathVariable String path) {
        FolderDO folderDO = repository.findBySelfPathName(path);
        FileCollection fileCollection = new FileCollection();
        if (folderDO == null) {
            return Result.error();
        }
        fileCollection.setName(folderDO.getName());
        fileCollection.setSiteSet(folderDO.getSites());
        fileCollection.setFolderSet(repository.findByParentId(folderDO.getId()));
        return Result.ok(fileCollection);
    }


}
